#!/bin/bash -v
# Create iot.cfg link 
#
# 遗留问题：脚本用的是专用模块，但这个模块电池无法自动充电，用几就要换
#          如果用陶晶驰内置的时间，屏内无电池，也无法保持。目前脚本暂时
#           用的时间模块，这个不用编程
#
##############################################################
SRC_DIR=/root/iot/
rm -rf /etc/iot

##################### Part 1: install packages(MUST!!!)
apt update

#Install paho 
apt install libpaho-mqtt1.3  libpaho-mqtt-dev paho.mqtt.c-examples -y
ln -s /usr/lib/aarch64-linux-gnu/libpaho-mqtt3c.so /usr/lib/libpaho-mqtt3c.so

#Install sqlite3
apt install sqlite3 -y
apt install libsqlite3-dev -y

##################### Part 1: install packages( options )
#Just for jetlinks platform
#Install openssl(Option: for calc md5,if use jetlink, it's MUST!!)
apt install openssl -y
ln -s /usr/lib/x86_64-linux-gnu/libcrypto.so.3 /usr/lib/libcrypto.so

#Just for HDMI platform
#Install libjpeg(Option: for fbv&hdmi drv)
apt install libjpeg-dev -y
apt install libpng-dev -y
# using for view picture, -q arg
apt install fim -y

#install others
apt install tcpdump -y
apt install telnet -y
apt install dos2unix -y
apt install ntpdate -y
#开发文档在线手册
apt install manpages-dev manpages-posix-dev manpages-zh -y

#Stop some service
systemctl disable openvpn.service
systemctl disable bluetooth.service
#systemctl disable dnsmasq.service
systemctl disable rpcbind.service
#systemctl disable resolvconf.service
#systemctl disable resolvconf-pull-resolved

##################### Part 3: set env （IMPORT!!!)
#如果没有打开i2c及uart，则通过配置文件追加
HARD_CONF_FILE=/boot/orangepiEnv.txt
if [ $(grep -c "i2c3" $HARD_CONF_FILE) -eq 0 ];then
   echo "overlays=ph-i2c3 ph-uart5" >> /boot/orangepiEnv.txt
fi

#修改fstab为只读，重启后起作用;第二行是先清除原来的修改，以便可以多次执行
sed -i 's/commit=600,/commit=0,/g' /etc/fstab
sed -i 's/ro,default/default/g' /etc/fstab
sed -i '/ \/ / s/default/ro,default/g' /etc/fstab  #只改/分区为只读

# set base evn
timedatectl set-timezone Asia/Shanghai
timedatectl set-ntp true

#fix config dnsname
systemctl disable systemd-resolved.service
echo "nameserver 8.8.8.8" > /etc/resolv.conf
chattr +i /etc/resolv.conf

# 配置文件准备
mkdir -p /etc/iot
rm -f /etc/iot/iot.cfg
cp  ${SRC_DIR}cfg/emqx.cfg /etc/iot/iot.cfg

# 增加service ds3231 rtc
cp ${SRC_DIR}rtc_ds1307  /etc/init.d
chmod a+x /etc/init.d/rtc_ds1307
ln -f -s /etc/init.d/rtc_ds1307 /etc/rc3.d/S01rtc_ds1307

#增加服务启动iot
cp ${SRC_DIR}iot.service /etc/systemd/system/iot.service
systemctl daemon-reload
systemctl enable iot.service

cd $SRC_DIR;make

##############################非必要设置
#Add git config
git config --global user.email "peterhu318@126.com"
git config --global user.name  "peterhu318"
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=36000'  # 缓存10小时
#git config --global credential.helper store  # 明文存储~/.git-credentials

#Make alias
cat <<EOF > /etc/profile.d/iot_profile.sh
alias rootrw='mount -o rw,remount /'
alias rootro='mount -o ro,remount /'
alias killiot='pkill daemon.sh;pkill iot;systemctl stop iot.service'
alias vicfg='rootrw;vi /etc/iot/iot.cfg;rootro'
alias chk1883='netstat -an | grep 1883'
alias iotlog='tail -f /var/log/iot.log'
EOF

auto_login_cli.sh root

#增加我自己的无线
#nmcli dev wifi connect "HUAWEI-NXP776" password "xxxx318"

#Add vim tab config
cat <<EOF >> /etc/vim/vimrc.local
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
set number
vnoremap <C-j> :m '>+1<CR>gv=gv
vnoremap <C-k> :m '<-2<CR>gv=gv
nmap <CR> o<Esc>
EOF

# Put my ssh key to orangepi
mkdir -p ~/.ssh
cat <<EOF >> /root/.ssh/authorized_keys
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBsMSfXfTuKBYcDMyKO8suUrwlBJ0J2cJG5i/z0qdOOR peterhu318@IOT
EOF
chmod 600 /root/.ssh/authorized_keys

# 设置iot产生的log文件进行回滚
cat <<EOF > /etc/logrotate.d/iot-custom
/var/log.hdd/iot.log {
    missingok
    notifempty
    copytruncate
    size 9M 
    rotate 3
    create 644 root root
    maxage 7
    ifempty
    dateext
    dateformat -%Y%m%d_%H%M%S
    su root root
}
EOF
cat <<EOF > /etc/cron.d/iot-logrotate
# 每3分钟运行一次 logrotate（注意指定配置文件）
*/3 * * * * root /usr/sbin/logrotate /etc/logrotate.d/iot-custom --state /var/lib/logrotate/iot.status
EOF

exit 0;
#===============================END===================================
#Add myself ntp server
mqtt_server=$(grep ^ADDRESS /etc/iot/iot.cfg | cut -d: -f2 | sed 's%//%%')
echo "server $mqtt_server iburst" >   /etc/chrony/sources.d/local-ntp-server.sources
echo "server cn.ntp.org.cn iburst" >> /etc/chrony/sources.d/local-ntp-server.sources
chronyc reload sources
